package com.jinzhi.jzapi.msg;

import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.wxconsts.WxPushConfigure;
import com.jinzhi.jzapi.msg.domain.TemplateData;
import com.jinzhi.jzapi.msg.domain.WxMssVoS;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
@Slf4j
public class WxPushServiceQcl {
    //用来请求微信的get和post
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MpConfigService mpConfigService;


    /**
     * 发送订阅消息
     * @param appId
     * @param openid
     * @param templateId
     * @param map
     * @return
     */
    public String sendMsgToUser(Integer appId, String openid, String templateId, Map<String, TemplateData> map, String page) {
        MpConfigDO mpConfigDO = mpConfigService.selectById(appId);
        if (null == mpConfigDO){
            throw new IFastApiException(ApiEnumError.getConfFail.getCodeStr());
        }
        //获取access_token
        String access_token = getAccess_token(mpConfigDO.getAppId(), mpConfigDO.getAppSecret());
        String url = WxPushConfigure.WX_SUBSCRIPTION_TEMP_URL;
        url = url.replace("${ACCESS_TOKEN}",access_token);

        //拼接推送的模版
        /*WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id(templateId);//模版id
        wxMssVo.setForm_id(formId);//formid
        wxMssVo.setEmphasis_keyword(emphasis_keyword);
        wxMssVo.setData(map);*/

        WxMssVoS wxMssVo = new WxMssVoS();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id(templateId);//模版id
        wxMssVo.setPage(page);
        wxMssVo.setData(map);
        wxMssVo.setLang("zh_CN");
        wxMssVo.setMiniprogram_state("formal");

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        log.error("小程序推送结果={}", responseEntity.getBody());
        return responseEntity.getBody();
    }

    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    private String getAccess_token(String appId, String appSecret) {
        //获取access_token
        String url = WxPushConfigure.WX_GET_ACCESS_TOKEN;
        url = url.replace("${APPID}",appId);
        url = url.replace("${APPSECRET}",appSecret);
        Map map = restTemplate.getForObject(url, Map.class);
        return map.get("access_token").toString();
    }

}
